package com.zhoux.minidao.aspect;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

public class SqlInterceptorIpml implements SqlInterceptor {
	Logger logger=Logger.getLogger(this.getClass());

	@Override
	public boolean onInsert(Field[] fields, Object obj) throws Exception {
		Map<Object,Object> map = new HashMap<Object, Object>();
		for (Field field : fields) {
			field.setAccessible(true);
			String fieldName=field.getName();
			if("createDate".equals(fieldName)){
				map.put("createDate", new Date());
			}
		}
		setFieldValue(map, obj);
		return false;
	}

	@Override
	public boolean onUpdate(Field[] fields, Object obj) throws Exception {
		// TODO Auto-generated method stub
		return false;
	}
	
	public static void setFieldValue(Map<Object, Object> map,Object bean) throws Exception{
		Class<?> cls=bean.getClass();
		Method methods[] = cls.getDeclaredMethods();
		Field[] Fields=cls.getDeclaredFields();
		
		for (Field field : Fields) {
			String fieldType=field.getType().getSimpleName();
			String fieldName=field.getName();
			String setMethod=parSetName(fieldName);
			//校验方法是否存在
			if(!checkMethod(methods,setMethod)){
				continue;
			}
			//校验集合中是否存在对应的key
			if (!map.containsKey(fieldName)) {
				continue;
			}
			Object value = map.get(fieldName);
			Method method=cls.getMethod(setMethod, field.getType());
			
			if(null!=value){
				if("String".equals(fieldType)){
					method.invoke(bean, String.valueOf(value));
				}else if("Double".equals(fieldType)){
					method.invoke(bean, Double.valueOf(value.toString()));
				}else if("int".equals(fieldType)){
					method.invoke(bean, Integer.valueOf(String.valueOf(value)));
				}else{
					method.invoke(bean, value);
				}
			}
		}
		
	}
	/**
	 * 校验方法是否存在
	 * @param methods
	 * @param setMethod
	 * @return
	 */
	private static boolean checkMethod(Method[] methods, String setMethod) {
		if(null!=methods)
		{
			for (Method method : methods) {
				if(method.getName().equals(setMethod)){
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * 生成对应的字段对应的set方法名
	 * @param fieldName
	 * @return
	 */
	private static String parSetName(String fieldName) {
		if(null==fieldName||"".equals(fieldName))
			return null;
		return "set"+fieldName.substring(0, 1).toUpperCase()+fieldName.substring(1);
	}
	/**
	 * 生成对应的字段对应的get方法名
	 * @param fieldName
	 * @return
	 */
	private static String parGetName(String fieldName) {
		if(null==fieldName||"".equals(fieldName))
			return null;
		return "get"+fieldName.substring(0, 1).toUpperCase()+fieldName.substring(1);
	}
	
	public static void main(String[] args) {
		System.out.println(parGetName("s"));
	}

}
